﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBScript;
using eBlog.Core;
using eBlog.Entity;
using eBlog.Common;
using System.Collections;
using eBlog.Service;

namespace eBlog.Web.Admin
{
    public partial class PostsManage : PageBase
    {
        IDBBase dal = DBFactory.GetDbProvider(); //初始化数据工厂
        protected void Page_Load(object sender, EventArgs e)
        {
            PageValidate.CheckAdminLogin(this);
            var s = SettingService.GetSetting();
            if (!Page.IsPostBack)
            {
                switch (action)
                {
                    case "add":
                        edit.Visible = true;
                        list.Visible = false;
                        bindType();
                        break;

                    case "edit":
                        edit.Visible = true;
                        list.Visible = false;
                        bindType();
                        ShowInfo();

                        break;
                    case "del":
                        delInfo();
                        break;
                    case "settop":
                        setTop();
                        BindList();
                        bindType();
                        break;
                    default:
                        edit.Visible = false;
                        list.Visible = true;
                        BindList();
                        break;
                }
            }
            else
            {
                if (action == "del")
                    delInfo();
            }
        }

        private void BindList()
        {
            int PageIndex;
            if (!int.TryParse(Request.Params["page"], out PageIndex)) { PageIndex = 1; }

            ArrayList attrs = dal.Where("CodeName is null").Page(PageIndex, PageSize).GetListAndCount<Posts>();

            List<Posts> lists = attrs[0] as List<Posts>;
            ListCount = (int)attrs[1];
            RPLIST.DataSource = lists;
            RPLIST.DataBind();
            PageNav.Text = Pager.PageInfo(ListCount, PageSize, PageIndex);
        }

        /// <summary>
        /// set top status of the posts
        /// </summary>
        private void  setTop()
        {
            Posts postsModel = dal.GetModel<Posts>(id);
            postsModel.TopStatus = 1;
            dal.Update(postsModel);
            MessageBox.ShowAndRedirect(this, "置顶成功!", Request.Url.AbsolutePath);
        }

        public void btnSave_Click(object sender, EventArgs e)
        {
            ArrayList strErrs = new ArrayList(); //Add时候必须用::分开控件名
            this.edit.Visible = true;
            if (this.txtTitle.Text == "")
            {
                strErrs.Add("txtTitle::Title不能为空，请输入字符！");
            }
            if (this.txtSummary.Text == "")
            {
                strErrs.Add("txtSummary::Summary不能为空，请输入字符！");
            }
            if (this.txtContent.Text == "")
            {
                strErrs.Add("txtContent::Content不能为空，请输入字符！");
            }
          
            if (this.txtTag.Text == "")
            {
                strErrs.Add("txtTag::Tag不能为空，请输入字符！");
            }

            if (strErrs.Count > 0)
            {
                string[] arrayErrs = (string[])strErrs.ToArray(typeof(string));
                string strErr = string.Join("\\n", arrayErrs);
                MessageBox.Show(this,strErr);
                ErrCodeStr.Value = strErr;
                return;
            }

            //int TypeID = int.Parse(Request.Form["ddlType"]);
            var value = this.ddlType.SelectedValue;
            int TypeID = int.Parse(Request.Form["ddlType"]);
            string Title = this.txtTitle.Text;
            //string Slug = this.txtSlug.Text;
            //string Imageurl = this.txtImageurl.Text;
            string Summary = this.txtSummary.Text;
            string Content = this.txtContent.Text;
            string tagsid = string.Empty;//tags id
           
            #region 处理标签
            
          
            if (!string.IsNullOrEmpty(txtTag.Text.Trim()))
            {
                string[] tags = txtTag.Text.Trim().Split(',');
                var wherecondition = string.Empty;
                foreach (string tag in tags)
                {
                    if(string.IsNullOrEmpty(wherecondition))
                    {
                        wherecondition = "'" + tag + "'";
                    }
                    else
                    {
                        wherecondition = wherecondition + "," + "'" + tag + "'";
                    }

                }
                List<Terms> hastags = dal.Where("Type=2 and Name in (" + wherecondition + ")").GetList<Terms>();

                for (int i = 0; i < tags.Length; i++)
                {
                    bool has = false;
                    foreach (var hastag in hastags)
                    {
                        if(hastag!=null)
                        {
                            if(hastag.Name==tags[i])
                            {
                                if (action != "edit")
                                {
                                    hastag.Count += 1;
                                    dal.Update(hastag);
                                }

                                has = true;

                                if(string.IsNullOrEmpty(tagsid))
                                {
                                    tagsid = hastag.ID.ToString();
                                }
                                else
                                {
                                    tagsid = tagsid + "," + hastag.ID;
                                }
                               
                            }
                        }
                    }

                    if(!has)
                    {
                        //确定数据库中不存在该 tags
                        var termsList= dal.Where("Name=@name").SetString("name", tags[i]).GetList<Terms>();
                        if(termsList.Count<=0)
                        {
                            Terms termsModel = new Terms();
                            termsModel.Name = tags[i];
                            termsModel.Description = tags[i];
                            termsModel.DisplayOrder = 100;
                            termsModel.Count = 1;
                            termsModel.Type = 2;
                            termsModel.Createdate = DateTime.Now;
                            var isSuccess = dal.Add(termsModel);
                            if (isSuccess > 0)
                            {
                                if (string.IsNullOrEmpty(tagsid))
                                {
                                    tagsid = isSuccess.ToString();
                                }
                                else
                                {
                                    tagsid = tagsid + "," + isSuccess;
                                }
                            }
                        }

                    }

                }


            }
            #endregion

            int CommentStatus = 1;
            if (this.chkCommentStatus.Checked)
            {
                CommentStatus = 0;
            }
            //string Tag = this.txtTag.Text;
            int TopStatus = 0;
            if (this.chkTopStatus.Checked)
            {
                TopStatus = 1;
            }
            bool TopShow = false;
            if (this.chkTopShow.Checked)
            {
                TopShow = true;
            }
            bool recommend = false;
            if (this.chkRecommend.Checked)
            {
                recommend = true;
            }

            if (action == "edit" && id > 0)
            {
                Posts model = dal.GetModel<Posts>(id); //为了不覆盖更新,先读出存在的数据再按需填充数据
                if (model.TypeID != TypeID && model.TypeID>0)
                {
                    //将以前的type 下的count 减去1
                    Terms typemodeltemp = dal.GetModel<Terms>(model.TypeID);
                    if (typemodeltemp.Count > 0)
                    {
                        typemodeltemp.Count -= 1;
                        dal.Update(typemodeltemp);
                    }
                    model.TypeID = TypeID;
                    //将当前的type 下的count 加1
                    Terms typemodel = dal.GetModel<Terms>(TypeID);
                    if (typemodel != null)
                    {
                        typemodel.Count += 1;
                        dal.Update(typemodel);
                    }
                }
               
                model.Title = Title;
                //model.Slug = Slug;
                //model.Imageurl = Imageurl;
                model.Summary = Summary;
                model.Content = Content;
                model.CommentStatus = CommentStatus;
                model.Tag = tagsid;
                model.Status = 1;
                model.TopStatus = TopStatus;
                model.UpdateDate = DateTime.Now;
                model.TopShow = TopShow;
                model.Recommend = recommend;
                dal.Update<Posts>(model);
                MessageBox.ShowAndRedirect(this, "修 改 完 成!", Referrer.Value);
                return;
            }
            else
            {
                Posts model = new Posts();  //添加数据,准备新的实体

                model.TypeID = TypeID;
                model.Title = Title;
                //model.Slug = Slug;
                //model.Imageurl = Imageurl;
                model.Summary = Summary;
                model.Content = Content;
                model.CommentStatus = CommentStatus;
                model.CommentCount = 0;
                model.ViewCount = 0;
                model.Tag = tagsid;
                model.Status = 1;
                model.Recommend = recommend;
                model.TopStatus = TopStatus;
                model.CreateDate = DateTime.Now;
                model.TopShow = TopShow;
                if (TypeID > 0)
                {
                   
                    model.TypeID = TypeID;
                    //将当前的type 下的count 加1
                    Terms terms = dal.GetModel<Terms>(TypeID);
                    if (terms != null)
                    {
                        terms.Count += 1;
                        dal.Update(terms);//update the terms'count

                    }
                }

                int isSuccess=  dal.Add(model);

                if(isSuccess>0)
                {
                    if (CacheService<List<Posts>>.IsCacheExist("PostList"))
                    {
                        CacheService<List<Posts>>.RemoveAllCache();

                    }
                }

                Response.Redirect(Request.Url.AbsolutePath + "#" + isSuccess); //ADD并 返回当前Uri绝对地址不带参数
                return;
            }

        }

        private void ShowInfo()
        {
            try { this.Referrer.Value = Request.UrlReferrer.PathAndQuery; }
            catch { }
            if (id > 0 && action == "edit")
            {
                Posts model = dal.GetModel<Posts>(id);
                this.txtTitle.Text = model.Title;
                //this.txtSlug.Text = model.Slug;
                //this.txtImageurl.Text = model.Imageurl;
                this.txtSummary.Text = model.Summary;
                this.txtContent.Text = model.Content;
                if (model.CommentStatus == 0)
                {
                    this.chkCommentStatus.Checked = true;
                }
               

                var tagList = dal.Where("id in (" + model.Tag + ")").GetList<Terms>();

                var tagstring = string.Empty;
                foreach (Terms tagModel in tagList)
                {
                    if(tagModel!=null)
                    {
                        if(string.IsNullOrEmpty(tagstring))
                        {
                            tagstring = tagModel.Name;
                        }
                        else
                        {
                            tagstring = tagstring + "," + tagModel.Name;
                        }
                    }
                }

                this.txtTag.Text = tagstring;

                if (model.TopStatus == 1)
                {
                    this.chkTopStatus.Checked = true;
                }
                if (model.TopShow)
                {
                    chkTopShow.Checked = true;
                }
                try
                {
                    // .Items.FindByValue(model.Role_ID.ToString()).Selected = true;
                    ddlType.Items.FindByValue(model.TypeID.ToString()).Selected = true;
                }
                catch { }
                this.btnSave.Text = "编 辑";
            }

        }




        private void delInfo()
        {
            string ids = PageValidate.Form("checkallid");
            if (!String.IsNullOrEmpty(ids))
            {
                //dal.From("vt_Posts", "").Where("id in (@ids)").SetString("ids", ids).Delete();
                dal.From("Posts", "").Where("id in (" + ids + ")").Delete();

            }
            else
            {
                dal.Delete<Posts>(id);
                // dal.Delete("Posts", "id", id);
            }

            if (CacheService<List<Posts>>.IsCacheExist("PostList"))
            {
                CacheService<List<Posts>>.RemoveAllCache();

            }

          //  WebScript.Alert(this.Page, "删除成功！");
            Response.Redirect(Request.Url.AbsolutePath); //返回当前Uri绝对地址不带参数
            return;
        }

        /// <summary>
        /// 绑定下拉列表
        /// </summary>
        private void bindType()
        {
            List<Terms> termlist = dal.Where("type=1").GetList<Terms>();
            if (termlist.Count > 0)
            {
                ddlType.Items.Clear();
                ddlType.Items.Add(new ListItem("无分类", "0"));
                foreach (Terms c in termlist)
                {
                    ddlType.Items.Add(new ListItem(c.Name + " (" + c.Count + ") ", c.ID.ToString()));
                }
            }

        }
    }
}